package com.adan.base.execption;

import com.adan.base.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 全局异常处理器
 * @date: 2023-06-01 14:30
 */

@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 拦截自定义异常
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(XcPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(XcPlusException e){
        log.error("系统异常：{}", e.getErrMessage());
        return new RestErrorResponse(e.getErrMessage());
    }

    /**
     * 拦截校验异常
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R validException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        //封装异常信息
        Map<String, String> errorMsg = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            //获取错误字段
            String field = fieldError.getField();
            // 获取错误信息
            String message = fieldError.getDefaultMessage();
            errorMsg.put(field, message);
        });
        return R.error(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR, CommonError.VALID_EXCEPTION.getErrMessage())
                .put("data", errorMsg);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e){
        log.error("系统未知异常：{}", e.getMessage());
        e.printStackTrace();
        if(e.getMessage().equals("不允许访问")){
            return new RestErrorResponse("没有操作此功能的权限");
        }
        return new RestErrorResponse(e.getMessage());
    }

}
